package com.yunfeisoft.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.applet.utils.KeyUtils;
import com.applet.utils.SpringContextHelper;
import com.yunfeisoft.business.model.Supplier;
import com.yunfeisoft.business.service.inter.SupplierService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

public class SupplierExcelListener extends AnalysisEventListener<Supplier> {

    private static final Logger logger = LoggerFactory.getLogger(SupplierExcelListener.class);

    private List<Supplier> list = new ArrayList<Supplier>();
    private String orgId;
    private String userId;

    public SupplierExcelListener(String orgId, String userId) {
        this.orgId = orgId;
        this.userId = userId;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param supplier
     * @param analysisContext
     */
    @Override
    public void invoke(Supplier supplier, AnalysisContext analysisContext) {
        if (StringUtils.isBlank(supplier.getName())) {
            return;
        }
        supplier.setId(KeyUtils.getKey());
        supplier.setOrgId(orgId);
        supplier.setCreateId(userId);
        supplier.setModifyId(userId);
        supplier.setBalance(supplier.getBalance() == null ? BigDecimal.ZERO : supplier.getBalance());

        list.add(supplier);
    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param analysisContext
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        if (CollectionUtils.isEmpty(list)) {
            return;
        }

        SupplierService supplierService = SpringContextHelper.getBean(SupplierService.class);
        supplierService.batchSave(list);
    }
}
